/// redis 工具
use std::{pin::Pin};

use redis::{Client, aio::AsyncStream,AsyncCommands};

// use super::config::Config;

const REDIS_DST: &str = "redis://127.0.0.1:6379";


type MyConnection = redis::aio::Connection<Pin<Box<dyn AsyncStream + Send + Sync>>>;


async fn get_my_conn() -> Result<MyConnection, String>{
    // let cfg = Config::from_env().expect("初始化项目配置失败").redis;
    
    let client = Client::open(REDIS_DST).map_err(|err| err.to_string())?;
    let conn = client
        .get_async_connection()
        .await
        .map_err(|err| err.to_string())?;

    Ok(conn)
}

pub async fn set(key:String, value:String) -> Result<String, String>{
    let mut conn = get_my_conn().await.map_err(|err| err.to_string())?;


    conn.set(key, value).await.map_err(|err| err.to_string())?;
    Ok("Successfully set!".to_string())
}

pub async fn get(key:String) -> Result<String, String> {
    let mut conn = get_my_conn().await.map_err(|err| err.to_string())?;
    let value = conn.get(key).await.map_err(|err| err.to_string())?;
    Ok(value)
}

pub async fn delete(key:String) -> Result<String,String> {
    let mut conn = get_my_conn().await.map_err(|err| err.to_string())?;
    conn.del(key).await.map_err(|err| err.to_string())?;


    Ok("Successfully delete!".to_string())
}